package com.huawei.cloud.phone.management.infrastructure.db.datasource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.Map;

@Slf4j
public class DynamicDataSource extends AbstractRoutingDataSource {
    private static final ThreadLocal<DataSourceName> DATASOURCE_NAME = new ThreadLocal<>();


    public DynamicDataSource(DataSource defaultDataSource, Map<Object, Object> allDataSource) {
        super();
        super.setDefaultTargetDataSource(defaultDataSource);
        super.setTargetDataSources(allDataSource);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        log.debug("use datasource {}", DATASOURCE_NAME.get());
        return DATASOURCE_NAME.get();
    }

    public static void setDatasourceName(DataSourceName datasourceName) {
        DATASOURCE_NAME.set(datasourceName);
    }

    public static void clearDataSourceName() {
        DATASOURCE_NAME.remove();
    }
}
